<template>
  <div class="vipdetail">
    <!-- 头部导航 -->
    <div class="header">
      <div class="back-icon" @click="goBack">
        <van-icon name="arrow-left" size="22" color="#e7bf9b" />
      </div>
      <div class="title">{{ t("user-vipdetail_title") }}</div>
    </div>
    <div class="viptop1">
      <!-- VIP等级信息 -->
      <div class="vip-info">
        <div class="vip-left">
          <div class="viptitle">
            {{ t("user-vipdetail_viptitle") }} {{ currentLevel }}
          </div>
          <div class="vipsubtitle">
            <div class="team-size">
              {{ t("user-vipdetail_ukuranTim")
              }}<text class="num">{{ teamSize }}</text>
            </div>
            <!-- <div class="score-info">
              <div class="team-size">
                {{ t("mall_available")
                }}<text class="num">{{ availableScore }}</text>
              </div>
              <div class="score-icon">
                <img
                  width="17"
                  height="17"
                  src="@/assets/images/vipimg/score.png"
                  alt="score"
                />
              </div>
            </div> -->
          </div>
        </div>

        <div class="vip-right">
          <div class="vip-badge">
            <img
              width="120"
              height="120"
              :src="'/images/vipImg/'+currentLevel+'.png'"
              alt="badge"
            />
          </div>
        </div>
      </div>

      <!-- 进度条 -->
      <div class="progress-section">
        <div class="progress-bar">
          <van-progress
            :percentage="progressPercentage"
            :stroke-width="5"
            color="#e2c4a9"
            track-color="rgba(34, 26, 24, 0.5)"
          />
        </div>
        <div class="level-text">Lv{{ currentLevel }}/Lv10</div>
        <div class="upgrade-btn">
          <van-button type="primary" size="small" @click="goToInvite">{{
            t("user-vipdetail_upgrade")
          }}</van-button>
        </div>
      </div>

      <!-- 升级提示 -->
      <div class="upgrade-info">
        <div class="upgrade-title">
          {{ t("user-vipdetail_untukUpgrade", { level: currentLevel + 1 }) }}
        </div>
        <div class="requirements">
          <!-- <div class="score-requirement">
            <div class="score-text">
              {{ t("user-vipdetail_masihPerlu") }}<text class="num">{{
                needScore
              }}</text>
            </div>
            <div class="score-icon">
              <img
                width="17"
                height="17"
                src="@/assets/images/vipimg/score.png"
                alt="score"
              />
            </div>
          </div> -->
          <div class="team-requirement">{{ t("user-vipdetail_teamRequirement") }} {{ needTeam }}</div>
        </div>
      </div>
    </div>

    <!-- 特权说明 -->
    <div class="privileges">
      <div class="privileges-title">Eksekuti kelas</div>
      <div class="privileges-grid">
        <div class="privilege-item">
          <div class="privilege-icon">
            <div class="imgbox">
              <img
                src="@/assets/images/vipimg/icon5.png"
                width="40"
                height="40"
                alt="privilege"
              />
            </div>
          </div>
          <div class="privilege-name">{{ t("user-vipdetail_hadiahPemeriksaanLebihTinggi") }}</div>
        </div>
        <!-- 02 -->
        <div class="privilege-item">
          <div class="privilege-icon">
            <div class="imgbox">
              <img
                src="@/assets/images/vipimg/icon6.png"
                width="40"
                height="40"
                alt="privilege"
              />
            </div>
          </div>
          <div class="privilege-name">{{ t("user-vipdetail_lebihKomisi") }}</div>
        </div>
        <!-- 03 -->
        <div class="privilege-item">
          <div class="privilege-icon">
            <div class="imgbox">
              <img
                src="@/assets/images/vipimg/icon7.png"
                width="40"
                height="40"
                alt="privilege"
              />
            </div>
          </div>
          <div class="privilege-name">{{ t("user-vipdetail_banyakKeuntungan") }}</div>
        </div>
      </div>
    </div>

    <!-- 等级说明 -->
    <div class="level-description">
      <div class="description-title">{{ t("user-vipdetail_deskripsiTingkatAnggota") }}</div>
      <div class="level-table">
        <div class="table-header">
          <div class="col">{{ t("user-vipdetail_viptitle") }}</div>
          <div class="col">{{ t("user-vipdetail_ukuranTim") }}</div>
          <!-- <div class="col">
            <div class="score-header">
              <span>{{ t("user-vipdetail_diperlukan") }}</span>
              <img
                width="17"
                height="17"
                src="@/assets/images/vipimg/score.png"
                alt="score"
              />
            </div>
          </div> -->
        </div>
        <div class="table-content">
          <div class="table-row" v-for="level in levelData" :key="level.lever">
            <div class="col">Level {{ level.lever }}</div>
            <div class="col">{{ level.teamSize }}</div>
            <!-- <div class="col">{{ level.score }}</div> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getUserInfo as fetchUserInfoApi, vipdetail } from "@/api/user";
import { showToast } from "vant";
import { onMounted, ref, watch } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();
const { t } = useI18n();
// 返回上一页
const goBack = () => {
  router.back();
};

// 解析localStorage中的用户信息
interface UserInfoType {
  minlevel?: number;
  un_indirect_people?: number;
  score?: number;
  team_size?: number;
  [key: string]: any;
}

const userInfo = ref<UserInfoType>({});
const loading = ref(false);

// 获取用户信息
const fetchUserInfo = async () => {
  loading.value = true;
  try {
    const { data: res } = await fetchUserInfoApi();
    if (res) {
      userInfo.value = res;
      // 更新相关数据
      currentLevel.value = Number(userInfo.value?.minlevel) || 0;
      availableScore.value = Number(userInfo.value?.score) || 0;
      teamSize.value = Number(userInfo.value?.un_indirect_people) || 0;
    } else {
      showToast(res?.msg || t('vipuser_err'));
    }
  } catch (error) {
    console.error("err", error);
    showToast(t('vipuser_err'));
  } finally {
    loading.value = false;
  }
};

// 当前等级信息
const currentLevel = ref(1);
const teamSize = ref(0);
const availableScore = ref(0);
const progressPercentage = ref(0);
const needScore = ref(0);
const needTeam = ref(0);

// 等级数据
const levelData = ref<any[]>([]);

// 计算还需分数和团队人数
function updateNeedFields() {
  if (!Array.isArray(levelData.value) || !userInfo.value) return;

  // 找到下一级的数据
  const nextLevel = levelData.value.find(
    (level) => Number(level.lever) === Number(currentLevel.value) + 1,
  );

  if (nextLevel) {
    // 当前拥有的
    const currentScore = Number(userInfo.value.score) || 0;
    const currentTeam = Number(userInfo.value.un_indirect_people) || 0;

    // 下一级要求的
    const nextTeamRequired = Number(nextLevel.teamSize);
    const nextScoreRequired = Number(nextLevel.score);

    // 计算还需要多少
    needTeam.value = Math.max(nextTeamRequired - currentTeam, 0);
    needScore.value = Math.max(nextScoreRequired - currentScore, 0);

    // 进度条显示当前星星数占下一级要求的百分比
    progressPercentage.value =
      nextScoreRequired > 0
        ? Math.min((currentScore / nextScoreRequired) * 100, 100)
        : 0;

    console.log("--", {
      currentScore,
      currentTeam,
      nextTeamRequired,
      nextScoreRequired,
      needScore: needScore.value,
      needTeam: needTeam.value,
      progressPercentage: progressPercentage.value,
    });
  } else {
    // 已经是最高等级
    needScore.value = 0;
    needTeam.value = 0;
    progressPercentage.value = 100;
  }
}

onMounted(() => {
  // 获取用户信息
  fetchUserInfo();

  // 获取等级数据
  vipdetail()
    .then((res) => {
      if (res && Array.isArray(res.data)) {
        levelData.value = res.data;
        // 数据都准备好后，计算需求字段
        updateNeedFields();
      }
    })
    .catch((err) => {
      console.error("err", err);
      showToast("Gagal mendapatkan data tahap");
    });
});

// 当用户信息或等级数据变化时重新计算
watch([() => userInfo.value, () => levelData.value], () => {
  if (userInfo.value && Array.isArray(levelData.value)) {
    updateNeedFields();
  }
});

// Add the goToInvite function
const goToInvite = () => {
  router.push("/user/invite");
};
</script>

<style scoped lang="less">
.vipdetail {
  min-height: 100vh;
  background-color: #221a18;
  color: #e7bf9b;
  font-family: Arial, sans-serif;
  .header {
    display: flex;
    align-items: center;
    height: 45px;
    margin-left: 12px;
    .back-icon {
      margin-right: 17px;
    }

    .title {
      font-size: 17px;
      font-weight: bold;
    }
  }
  .viptop1 {
    min-width: 300px;
    max-width: 402px;
    height: 264px;
    background-image: url("@/assets/images/vipimg/bg01.png");
    margin: 5px 12px;
    border-radius: 8px;
    padding: 10px;
    background-size: 100% 100%;
    background-position: 50%;
    background-repeat: no-repeat;
    color: #caa196;

    .vip-info {
      margin-top: 75px;
      display: flex;
      justify-content: space-between;

      .vip-left {
        width: 60%;

        .viptitle {
          font-size: 28px;
          font-weight: bold;
          margin-bottom: 5px;
          color: #4a8eda;
        }

        .vipsubtitle {
          font-size: 13px;
          .team-size {
            margin-bottom: 5px;
            color: #6b9edf;
          }

          .score-info {
            display: flex;
            align-items: center;
          }

          .num {
            margin-left: 2px;
            color: #ff0000;
            font-weight: 600;
          }
        }
      }

      .vip-right {
        width: 40%;
        position: relative;

        .vip-badge {
          position: absolute;
          top: -65px;
          right: 20px;
        }
      }
    }

    .progress-section {
      // margin-top: 10px;
      margin-top: 25px;
      display: flex;
      align-items: center;

      .progress-bar {
        width: 60%;
      }

      .level-text {
        width: 10%;
        padding-left: 8px;
        font-size: 12px;
        color: #000;
      }

      .upgrade-btn {
        width: 100px;
        display: flex;
        justify-content: flex-end;

        :deep(.van-button) {
          background: #ffffff;
          border: none;
          border-radius: 15px;
          color: #221a18;
          font-weight: 500;
          padding: 0 10px;
        }
      }
    }

    .upgrade-info {
      margin-top: 5px;
      font-size: 14px;
      color: #333333;
      .requirements {
        display: flex;
        margin-top: 3px;

        .score-requirement {
          display: flex;
          align-items: center;
          margin-right: 34px;
        }

        .num {
          margin-left: 2px;
          color: #e7bf9b;
        }
      }
    }
  }

  .privileges {
    margin: 17px;
    padding: 11px 5px;
    border-radius: 8px;
    background-color: rgba(254, 242, 230, 0.05);
    border: 0.5px solid rgba(153, 153, 153, 0.3);

    .privileges-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 11px;
      padding-left: 5px;
    }

    .privileges-grid {
      display: flex;
      justify-content: space-around;

      .privilege-item {
        width: 33%;
        white-space: pre-wrap;
        word-wrap: break-word;
        font-size: 12px;
        color: #dab082;
        text-align: center;
        padding-top: 6px;
        .privilege-icon {
          .imgbox {
            width: 51px;
            height: 51px;
            border-radius: 28px;
            display: block;
            margin: 0 auto;
            background: linear-gradient(0deg, #b48b5f, #eed8bd);
            img {
              width: 40px;
              height: 40px;
              border-radius: 28px;
              margin-top: 5px;
            }
          }
        }
        .privilege-name {
          font-size: 12px;
          margin-top: 5px;
        }
      }
    }
  }

  .level-description {
    padding: 0 17px;

    .description-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .level-table {
      background-color: rgba(34, 26, 24, 0.8);
      border-radius: 9px;
      padding: 14px;
      font-size: 12px;
      color: #aec4e1;

      .table-header {
        display: flex;
        color: #aec4e1;
        margin-bottom: 5px;
        padding: 0 11px;

        .col {
          flex: 1;
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }

      .table-content {
        .table-row {
          display: flex;
          padding: 5px 11px;
          border-bottom: 0.5px solid rgba(153, 153, 153, 0.3);

          .col {
            flex: 1;
            color: #e7bf9b;
          }
        }
      }
    }
  }
}
</style>
